from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.utils.urls import replace_query_param
from rest_framework.viewsets import ModelViewSet

from av_manager import models
from av_manager.serializers import PlatFormSerializer, ChannelSubscriptionSerializer, CarriedContentSerializer
from av_manager.tasks import carry_video


class PlatFormViewSet(ModelViewSet):
    queryset = models.PlatForm.objects.all()
    serializer_class = PlatFormSerializer

    @action(methods=["GET"], detail=True)
    def get_channel_by_id(self, request, *args, **kwargs):
        instance = self.get_object()
        channel_id = request.GET.get("channel_id")
        manager = instance.get_manager()
        data = manager.get_brief_channel_by_id(channel_id)
        return Response(data)

    @action(methods=["GET"], detail=True)
    def get_channel_videos(self, request, *args, **kwargs):
        instance = self.get_object()
        page_type = request.GET.get("page_type", "page_token")
        # page_token = request.GET.get("page_token")
        channel_id = request.GET.get("channel_id")
        keyword = request.GET.get("keyword")
        manager = instance.get_manager()
        data = manager.get_videos_in_channel(channel_id=channel_id, keyword=keyword)
        url = self.request.build_absolute_uri()
        data["next"] = replace_query_param(url, page_type, data.get("next")) if data.get("next") else None
        data["previous"] = replace_query_param(url, page_type, data.get("previous")) if data.get("previous") else None
        return Response(data)

    @action(methods=["GET"], detail=True)
    def get_channel_video_detail(self, request, *args, **kwargs):
        instance = self.get_object()
        manager = instance.get_manager()
        video_id = request.GET.get("video_id")
        data = manager.get_video_detail(video_id=video_id)
        return Response(data)


class ChannelSubscriptionViewSet(ModelViewSet):
    queryset = models.ChannelSubscription.objects.all()
    serializer_class = ChannelSubscriptionSerializer


class CarriedContentViewSet(ModelViewSet):
    queryset = models.CarriedContent.objects.all()
    serializer_class = CarriedContentSerializer

    def perform_create(self, serializer):
        serializer.save()
        ins = serializer.instance
        if ins.content_type == models.PLAT_CONTENT_VIDEO:
            carry_video.delay(plat_id=ins.channel.plat_from_id, carry_content_id=ins.id, video_id=ins.content_id,
                              video_name=ins.name)
